import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { tenantUserEnum, orderStatusEnum } from '~/store/oam/typings'
import type { OrderManageFormValuesType, OrderManageStateType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElSpace,
  ElButton,
  ElLink
} from 'element-plus'
import ProSaasTable from '~/components/ProSaasTable'
import ColorfulBadge from '~/components/ColorfulBadge'
import OrderMap from './orderMap'
import OrdersUpdate from './OrdersUpdate'
import OrderManageOptions from './options'
import AliIcon from '~/components/AliIocn'
import useVuexGetters from '~/hooks/useVuexGetters'
// import styles from '../index.module.scss'

export default defineComponent(function OrderManage() {
  const store = useStore()
  const route = useRoute()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<OrderManageFormValuesType>({})
  const state = reactive<OrderManageStateType>({
    countAll: undefined,
    countToday: undefined,
    orderMapVisible: false,
    visible: false,
    optionVisible: false
  })
  const orderState = useVuexGetters('order', [
    'orderStatusSelectList',
    'tenantUserSelectList',
    'orderStatusEnum',
    'tenantUserEnum',
    'deptTreeEnum',
    'appointmentTimeEnum'
  ])

  // 切换地图与列表展示
  const handleChangeOrderMapVisible = () => {
    state.orderMapVisible = !state.orderMapVisible
  }

  // 获取工单历史统计数据
  const handleGetOrderCountInfo = () => {
    store.dispatch('order/GetOrderCountInfo').then((res) => {
      state.countAll = res?.data?.countAll ?? 0
      state.countToday = res?.data?.countToday ?? 0
    })
  }
  // 切换工单查看弹框
  const handleChangeOptionsVisible = (row?: OrderManageFormValuesType) => {
    state.visible = !state.visible
    state.record = row
    if (!state.visible) proSaasTableRef?.value?.toSearch()
    // router.push({ path: '/oam/orderManage/options', query: { id: row?.id } })
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  // 获取工单详情
  const handleGetOrderInfo = async (id: string) => {
    const res = await store.dispatch('order/GetOrderInfo', { id })
    if (!res?.success || !res?.data) return
    state.visible = true
    state.record = res?.data || {}
  }

  // 打开工单操作
  const handleChangeOrderOption = (patrolRecordId?: string) => {
    state.optionVisible = !state.optionVisible
    state.record = patrolRecordId ? { patrolRecordId } : {}
  }

  onMounted(async () => {
    store.dispatch('order/GetOrderTypeSelectList')
    store.dispatch('order/GetTenantUserSelectList')
    store.dispatch('order/GetDeptTreeSelectList')
    handleGetOrderCountInfo()

    if (route.query.id) handleGetOrderInfo(route.query.id as string)
    if (route.query.patrolRecordId || route.query.type === 'add')
      handleChangeOrderOption(route.query.patrolRecordId as string)
  })

  const columns: TableColumnProps<OrderManageFormValuesType>[] = [
    {
      label: '报修来源',
      prop: 'repairResourceName',
      minWidth: 160,
      fixed: 'left',
      unFixed: true,
      showOverflowTooltip: true
    },
    {
      label: '工单状态',
      prop: 'orderStatus',
      minWidth: 140,
      enumValues: orderState.orderStatusEnum,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.orderStatus as number}
          // options={{ danger: 0, warning: 1, success: 5 }}
        />
      )
    },
    {
      label: '报修内容',
      prop: 'suppleMemo',
      minWidth: 180,
      showOverflowTooltip: true
    },
    {
      label: '处理人',
      prop: 'handleUserName',
      minWidth: 120
      // enumValues: orderState.tenantUserEnum
    },
    {
      label: '计划完单时间',
      prop: 'planCompleteTime',
      minWidth: 220,
      showOverflowTooltip: true
    },
    {
      label: '出单时间',
      prop: 'createTime',
      minWidth: 220,
      showOverflowTooltip: true
    },
    {
      label: '完单时长',
      prop: 'completeTimeLength',
      minWidth: 220,
      showOverflowTooltip: true
    },
    {
      label: '是否约时',
      prop: 'isArrange',
      minWidth: 140,
      enumValues: orderState.appointmentTimeEnum
    },
    {
      label: '设备运维区域',
      prop: 'handleDeptId',
      minWidth: 170,
      enumValues: orderState.deptTreeEnum
    },
    {
      label: '出单人',
      prop: 'createUserName',
      minWidth: 120
      // enumValues: orderState.tenantUserEnum
    },
    {
      label: '出单时长',
      prop: 'createTimeLength',
      minWidth: 220,
      showOverflowTooltip: true
    },
    {
      label: '操作',
      prop: 'options',
      align: 'center',
      fixed: 'right',
      unFixed: true,
      width: 150,
      render: ({ row }) => (
        <ElSpace>
          <ElLink type="primary" onClick={() => handleChangeOptionsVisible(row)}>
            <AliIcon type="icon-chakan" />
            &nbsp; 查看
          </ElLink>
        </ElSpace>
      )
    }
  ]

  return () => {
    if (state.orderMapVisible) {
      return <OrderMap handleChangeOrderMapVisible={handleChangeOrderMapVisible} />
    }

    if (state.visible) {
      return (
        <OrderManageOptions
          visible={state.visible}
          record={state.record}
          cancel={handleChangeOptionsVisible}
        />
      )
    }

    if (state.optionVisible) {
      return (
        <OrdersUpdate
          title={state.record?.id ? '编辑工单' : '新增工单'}
          showOrdersUpdate={state.optionVisible}
          info={state.record}
          cancel={() => handleChangeOrderOption()}
        />
      )
    }

    return (
      <ElCard>
        <ProSaasTable<OrderManageFormValuesType>
          ref={proSaasTableRef}
          columns={columns}
          searchParams={formValues}
          searchFormProps={{
            model: formValues
          }}
          searchformResponsiveCol={[
            <ElFormItem key="keyWord" prop="keyWord" label="关键字">
              <ElInput
                v-model={formValues.keyWord}
                placeholder="请输入工单编号/95598编号/报修内容"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="handleUserId" prop="handleUserId" label="处理人">
              <ElSelect v-model={formValues.handleUserId} clearable onChange={clearSearchTable}>
                {orderState.tenantUserSelectList?.value?.map((item: tenantUserEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="createUser" prop="createUser" label="出单人">
              <ElSelect v-model={formValues.createUser} clearable onChange={clearSearchTable}>
                {orderState.tenantUserSelectList?.value?.map((item: tenantUserEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="orderStatus" prop="orderStatus" label="工单状态">
              <ElSelect v-model={formValues.orderStatus} clearable onChange={clearSearchTable}>
                {orderState.orderStatusSelectList?.value?.map((item: orderStatusEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
                ))}
              </ElSelect>
            </ElFormItem>
          ]}
          dispatchType="order/GetOrderList"
        >
          <p>
            <ElButton
              type="primary"
              icon={<AliIcon type="icon-qiehuandituzhanshi" />}
              onClick={handleChangeOrderMapVisible}
            >
              切换地图显示
            </ElButton>
          </p>
        </ProSaasTable>
      </ElCard>
    )
  }
})
